import { CommonModule } from '@angular/common';
import { Component, Inject } from '@angular/core';
import { AbstractControl, FormControl, FormGroup, FormsModule, ReactiveFormsModule, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogActions, MatDialogClose, MatDialogContent, MatDialogTitle } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { file, fileInfoBaseDto, folder } from 'ispace.core.main';

@Component({
  selector: 'app-rename-cmp',
  standalone: true,
  imports: [ 
    MatFormFieldModule, 
    MatButtonModule,
    MatDialogTitle,
    MatDialogContent,
    MatDialogActions, 
    CommonModule,
    FormsModule,
    MatInputModule, 
    ReactiveFormsModule
  
  ],
  templateUrl: './rename-cmp.component.html',
  styleUrl: './rename-cmp.component.scss'
})
export class  RenameCmpComponent {
  constructor( public dialogRef: MatDialogRef<RenameCmpComponent>,
    @Inject(MAT_DIALOG_DATA) public data: fileInfoBaseDto,) { 
      this.nameFormControl =  new FormControl<string>(this.data.name || ''), {
        validators: [
          Validators.required,
          this.namePatternValidator()
        ] };
  
    }
  
  nameFormControl!:FormControl<string|null>;
  
  private namePatternValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const originalName = this.data.name;
      if (control.value === originalName) {
        return { 'nameMismatch': true };
      }
      return null;
    };
  }

  onYesClick() { 
      if (this.nameFormControl.valid) {
       
        const parentPath = this.data.path!.substring(0, this.data.path!.lastIndexOf('/'))!;
      // Perform the rename operation
      if(this.data.isDir) { 
        folder.rename(parentPath,this.data.name!,this.nameFormControl.value!).subscribe({
          next: () => {
            this.data.name = this.nameFormControl.value!;
            this.dialogRef.close(true);
          },error: (err) => {
            alert('Error renaming folder: ' + err.message);
            this.dialogRef.close(false);
          }
        });
      }
      else {
        file.rename(parentPath, this.data.name!, this.nameFormControl.value!).subscribe({
          next: () => {
            this.data.name = this.nameFormControl.value!;
            this.dialogRef.close(true);
          },error: (err) => {
            alert('Error renaming file: ' + err.message);
            this.dialogRef.close(false);
          } });
      } 
      }  
  }

  onNoClick(): void {
    this.dialogRef.close(false);
  }
}
 